<template>
  <div class="about">
    <div class="header">
      <!-- 折叠按钮 -->
      <div class="collapse-btn" @click="collapseChage">
        <i v-if="!collapse" class="el-icon-s-fold"></i>
        <i v-else class="el-icon-s-unfold"></i>
      </div>

      <div class="header-system">
        <el-menu
            :default-active="activeSystem"
            mode="horizontal"
            background-color="#324157"
            text-color="#bfcbd9"
            active-text-color="#20a0ff">
          <el-menu-item
              v-for="(item, i) in systemList"
              :key="item.id"
              :index="i"
              @click="loadListMenu(item.id)"
          >{{ item.name }}
          </el-menu-item>
        </el-menu>
      </div>

      <div class="header-right">
        <div class="header-user-con">
          <div class="header-org-select">
            <el-select
                v-model="userOrgId"
                placeholder="请填写所属组织"
                class="handle-select mr10"
                clearable
                filterable
                @change="editChangeOrg"
            >
              <el-option
                  v-for="item in orgList"
                  :key="item.userOrgId"
                  :label="item.abbr"
                  :value="item.userOrgId"
              ></el-option>
            </el-select>
          </div>

          <!-- 全屏按钮 -->
          <div class="btn-fullscreen" @click="clickFullscreen">
            <el-tooltip effect="dark" :content="`全屏`" placement="bottom">
              <i class="el-tooltip el-icon-rank"></i>
            </el-tooltip>
          </div>
          <!-- 消息中心 -->
          <div class="btn-bell">
            <el-tooltip
                effect="dark"
                content="有新消息"
                placement="bottom"
            >
              <router-link to="/message">
                <i class="el-icon-bell"></i>
              </router-link>
            </el-tooltip>
            <span class="btn-bell-badge" v-if="message"></span>
          </div>
          <!-- 用户头像 -->
          <div class="user-avator">
            <img :src="userInfo.avatarStr"/>
          </div>
          <!-- 用户名下拉菜单 -->
          <el-dropdown class="user-name" trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
            {{ userInfo.realName ? userInfo.realName : userInfo.username }}
            <i class="el-icon-caret-bottom"></i>
          </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item divided command="monitor">
                  <el-link
                      href="http://monitor.iwindplus.com"
                      target="_blank"
                      :underline="false"
                      type="info"
                  >
                    微服务监控
                  </el-link>
                </el-dropdown-item>
                <el-dropdown-item divided command="registerCenter">
                  <el-link
                      href="https://nacos.iwindplus.com/nacos"
                      target="_blank"
                      :underline="false"
                      type="info"
                  >
                    注册中心
                  </el-link>
                </el-dropdown-item>
                <el-dropdown-item divided command="FluidControl">
                  <el-link
                      href="https://sentinel.iwindplus.com"
                      target="_blank"
                      :underline="false"
                      type="info"
                  >
                    流控
                  </el-link>
                </el-dropdown-item>
                <el-dropdown-item divided command="ServerLinkTrack">
                  <el-link
                      href="https://seata.iwindplus.com"
                      target="_blank"
                      :underline="false"
                      type="info"
                  >
                    分布式事务
                  </el-link>
                </el-dropdown-item>
                <el-dropdown-item divided command="ServerLinkTrack">
                  <el-link
                      href="https://kibana.iwindplus.com"
                      target="_blank"
                      :underline="false"
                      type="info"
                  >
                    日志
                  </el-link>
                </el-dropdown-item>
                <el-dropdown-item divided command="ApiDoc">
                  <el-link
                      href="https://api.iwindplus.com/doc.html"
                      target="_blank"
                      :underline="false"
                      type="info"
                  >
                    api文档
                  </el-link>
                </el-dropdown-item>
                <el-dropdown-item divided command="editPass"
                >编辑密码
                </el-dropdown-item>
                <el-dropdown-item divided command="logout"
                >退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <div class="sidebar">
      <el-menu
          class="sidebar-el-menu"
          :default-active="onRoutes"
          :collapse="collapse"
          background-color="#324157"
          text-color="#bfcbd9"
          active-text-color="#20a0ff"
          unique-opened
          router
      >
        <template v-for="item in menuList">
          <template v-if="item.children && item.children.length">
            <el-submenu :index="item.id" :key="item.id">
              <template #title>
                <i :class="item.iconStyle"></i>
                <span>{{ item.name }}</span>
              </template>
              <template v-for="subItem in item.children">
                <el-submenu
                    v-if="subItem.children && subItem.children.length"
                    :index="subItem.routeUrl"
                    :key="subItem.id"
                >
                  <template #title>{{ subItem.name }}</template>
                  <el-menu-item
                      v-for="(threeItem, i) in subItem.children"
                      :key="i"
                      :index="threeItem.id"
                  >{{ threeItem.name }}
                  </el-menu-item>
                </el-submenu>
                <el-menu-item v-else :index="subItem.routeUrl" :key="subItem.id">{{
                    subItem.name
                  }}
                </el-menu-item>
              </template>
            </el-submenu>
          </template>
          <template v-else>
            <el-menu-item :index="item.routeUrl" :key="item.id">
              <i :class="item.iconStyle"></i>
              <template #title>{{ item.name }}</template>
            </el-menu-item>
          </template>
        </template>
      </el-menu>
    </div>

    <div class="content-box" :class="{ 'content-collapse': collapse }">
      <v-tags></v-tags>
      <div class="content">
        <router-view v-slot="{ Component }">
          <transition name="move" mode="out-in">
            <keep-alive :include="tagsList">
              <component :is="Component"/>
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>

  <!-- 编辑密码弹出框 -->
  <el-dialog
      title="编辑密码"
      v-model="editVisible"
      :rules="rules"
      ref="editPass"
      width="30%"
      @closed="closed"
      @keyup.enter="editPass()"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="70px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
            type="password"
            placeholder="请输入旧密码"
            v-model="form.oldPassword"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
            type="password"
            placeholder="请输入新密码"
            v-model="form.newPassword"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editPass">确 定</el-button>
        </span>
    </template>
  </el-dialog>

  <!--消息弹出框 -->
  <el-dialog
      :title="messageForm.title"
      v-model="messageVisible"
      :rules="rules"
      ref="message"
      width="50%">
    <el-form ref="messageForm" :model="messageForm" :rules="rules" label-width="210px">
      <el-form-item label="消息类型：">
        <div>
          {{ $enum.getMapValue("command", messageForm.command).name }}
        </div>
      </el-form-item>
      <el-form-item label="消息：">
        <el-input v-if="visible" v-model="messageForm.id"/>
        <div v-text="messageForm.content"></div>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="messageDetail()">详情</el-button>
        </span>
    </template>
  </el-dialog>
</template>
<script>

import store from "@/store";
import vTags from "../components/Tags.vue";
import screenfull from "screenfull";
import {deepCopy, logoutClear} from "../utils";
import {logoutApi} from "../api/mgt/power/auth";
import {userEditChangeOrgApi, userEditPasswordApi, userGetUserInfoApi,} from "../api/mgt/power/user";
import {orgListByUserIdApi} from "../api/mgt/power/org";
import {menuListByUserId} from "../api/mgt/power/menu";

import websocket from '@/utils/websocket';

const websocketEnabled = process.env.VUE_APP_WEBSOCKET_ENABLED;

const obj = {
  //信息
  oldPassword: "",
  newPassword: "",
};

const msgObj = {
  //信息
  command: "",
  title: "",
  content: "",
};

export default {
  data() {
    return {
      activeSystem: '',
      dataList: [],
      systemList: [],
      menuList: [],
      orgList: [],
      editVisible: false,
      messageVisible: false,
      systemId: null,
      userOrgId: null,
      form: deepCopy(obj),
      messageForm: deepCopy(msgObj),
      rules: {
        oldPassword: [
          {required: true, message: "请输入旧密码", trigger: "blur"},
        ],
        newPassword: [
          {required: true, message: "请输入新密码", trigger: "blur"},
        ],
      },
    };
  },
  components: {
    vTags,
  },
  computed: {
    tagsList() {
      return this.$store.state.tagsList.map(item => item.name);
    },
    collapse() {
      return this.$store.state.collapse;
    },
    onRoutes() {
      return this.$route.path;
    },
    userInfo() {
      return this.$store.state.userInfo;
    }
  },
  methods: {
    listData() {
      menuListByUserId().then((res) => {
        this.dataList = res?.bizData;
        this.systemList = this.dataList.map(item => ({
          id: item.id,
          name: item.name,
        }));
        this.activeSystem = 0;
        this.loadListMenu(this.systemList[0].id)
      });
    },
    loadListMenu(systemId) {
      const matchedSystem = this.dataList.find(item => item.id === systemId);
      if (matchedSystem && matchedSystem.menus) {
        this.menuList = matchedSystem.menus;
      }
    },
    async getSocketResult(data) {
      if (data.command === "PERSON_NOTICE_MSG") {
        if (data.subMsgType === 'refresh_role_permission') {
          console.log(data)
          // 刷新角色权限
        } else if (data.subMsgType === 'refresh_button_permission') {
          // 刷新按钮权限
          console.log(data)
        }
      } else if (data.command === "REFRESH_PERMISSION_MSG") {
        userGetUserInfoApi().then((res) => {
          const data = res?.bizData;
          if (data != undefined && data != null && data != '') {
            store.commit("setUserInfo", data);
          }
        });
      } else {
        this.messageVisible = true;
        this.messageForm = data;
      }
    },
    messageDetail() {
      this.messageVisible = false;
      let command = this.messageForm.command;
      let id = this.messageForm.id;
      this.$router.goPage({
        path: "/message",
        query: {
          command,
          id,
        },
      });
    },
    // 获取组织数据
    getOrgData() {
      orgListByUserIdApi().then((res) => {
        this.orgList = res?.bizData;
        this.orgList.forEach((item) => {
          if (item.checked) {
            this.userOrgId = item.userOrgId;
          }
        });
      });
    },
    // 切换组织
    editChangeOrg(userOrgId) {
      userEditChangeOrgApi({userOrgId: userOrgId}).then((res) => {
        this.$router.goPage({
          path: "/dashboard",
        });

        const tips = "切换组织成功，一秒后跳至主页";
        this.$message.success({
          message: tips,
          duration: 1 * 1000,
          onClose: () => {
            window.location.reload();
          },
        });
      });
    },
    // 用户名下拉菜单选择事件
    handleCommand(command) {
      if (command == "logout") {
        this.$confirm("您确定要退出吗？", "提示", {
          type: "warning",
        }).then(() => {
          this.logout();
        });
      } else if (command == "editPass") {
        // 编辑密码
        this.editVisible = true;
      }
    },
    // 侧边栏折叠
    collapseChage() {
      this.$store.commit("hadndleCollapse", !this.collapse);
    },
    // 全屏
    clickFullscreen() {
      if (screenfull.isEnabled) {
        screenfull.toggle();
      }
    },
    // 退出
    logout() {
      logoutApi().then(() => {
        this.$message.success({
          message: "退出成功",
          duration: 1000,
          onClose: () => {
            logoutClear();
          },
        });
      });
    },
    // 编辑密码
    editPass() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          userEditPasswordApi(this.form).then((res) => {
            this.editVisible = false;
            this.$message.success("编辑密码成功");

            logoutClear();
          });
        } else {
          return false;
        }
      });
    },
  },
  created() {
    this.listData();
    this.getOrgData();

    if (websocketEnabled === 'true') {
      // 初始化 WebSocket 连接并设置接收消息的回调
      websocket.initSocket(this.getSocketResult);

      // 可选：监听连接状态变化
      websocket.onStatusChange((status) => {
        console.log('WebSocket 状态变化:', status);
        if (status === 'connected') {
          // 连接成功后可以发送初始消息或订阅事件
          websocket.sendSocket({command: "OFFLINE_DIRECT_MSG"});
        }
      });
    }
  },
};
</script>

<style scoped>
.header {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 50px;
  font-size: 22px;
  color: #fff;
}

.collapse-btn {
  float: left;
  padding: 0 21px;
  cursor: pointer;
  line-height: 50px;
}

.header .header-system {
  float: left;
  cursor: pointer;
  line-height: 50px;
  height: 50px;
}

.header-right {
  float: right;
  padding-right: 50px;
}

.header-org-select {
  margin-right: 5px;
  font-size: 24px;
}

.header-user-con {
  display: flex;
  height: 50px;
  align-items: center;
}

.btn-fullscreen {
  transform: rotate(45deg);
  margin-right: 5px;
  font-size: 24px;
}

.btn-bell,
.btn-fullscreen {
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
  border-radius: 15px;
  cursor: pointer;
}

.btn-bell-badge {
  position: absolute;
  right: 0;
  top: -2px;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #f56c6c;
  color: #fff;
}

.btn-bell .el-icon-bell {
  color: #fff;
}

.user-name {
  margin-left: 10px;
}

.user-avator {
  margin-left: 20px;
}

.user-avator img {
  display: block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.el-dropdown-link {
  color: #fff;
  cursor: pointer;
}

.el-dropdown-menu__item {
  text-align: center;
}

.sidebar {
  display: block;
  position: absolute;
  left: 0;
  top: 50px;
  bottom: 0;
  overflow-y: scroll;
}

.sidebar::-webkit-scrollbar {
  width: 0;
}

.sidebar-el-menu:not(.el-menu--collapse) {
  width: 200px;
}

.sidebar > ul {
  height: 100%;
}
</style>
